package com.jl;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据持久化工具类
 */
public class JLDataUtil {

    /**
     * 读
     */
    public static List<String> read(String name) {
        String dataPath = getDataPath(name);
        File file = new File(dataPath);
        if (file.isFile() && file.exists()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String data;
                List<String> result = new ArrayList<>();
                while ((data = bufferedReader.readLine()) != null) {
                    result.add(data);
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 写
     */
    public static boolean write(List<String> result, String name) {
        String dataPath = getDataPath(name);
        boolean flag = false;
        BufferedWriter out = null;
        try {
            File file = new File(dataPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK"));
            for (String info : result) {
                out.write(info);
                out.newLine();
            }
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 删除
     *
     * @param name
     */
    public static void remove(String name) {
        String dataPath = getDataPath(name);
        new File(dataPath).delete();
    }

    /**
     * 获取文件路径
     *
     * @param name
     * @return
     */
    private static String getDataPath(String name) {
        String dataPath = System.getProperty("user.dir") + "/data/" + name + ".jl";
        return dataPath;
    }
}
